<?php
namespace Tongcheng\Controller;
use Think\Controller;
class CommissionController extends CommonController {
    public function index(){
    	$model = M("Coupon");
    	$map['tp_coupon.wid'] = session('wid');
        $map['tp_coupon.status'] = 1;
    	$list = $model->field("tp_coupon.*,s.name")->join("tp_shop s on s.shop_id = tp_coupon.shop_id")->where($map)->select();
        foreach($list as $k=>$v){
            $tui = M("tui")->where(['wid'=>session('wid'),'aid'=>$v['id'],"type"=>'coupon'])->find();
            if(!$tui || !$tui['status']){
                $list[$k]['is_tui'] = 0;
            }else{
                $list[$k]['is_tui'] = 1;
            }
        }
        $this->assign("list",$list);
        $this->display();
    }
    //基础设置
    public function set(){
        //修改
        $eq['wid'] = session('wid');
        if(I('good_commission')){
            $data['good_commission'] = I('good_commission');//支付后1 核销2
            $data['commission_level'] = I('commission_level');//1一级分销 2二级分销
            $data['leader_money'] = I('leader_money');//成为队长金额
            $data['leader_people'] = I('leader_people');//成为队长团队人数
            $data['leader_commission'] = I('leader_commission');//成为队长佣金额度
            $data['decimation_ratio'] = I('decimation_ratio');//佣金提现平台抽取比例
            $data['leader_bonus'] = I('leader_bonus');//队长分红比例
            $data['team_withdraw'] = I('team_withdraw');//团队提现抽成比例

            if(M('wechat')->where($eq)->save($data)){
                $this->success('修改成功！');
            }else{
                $this->error('网络忙');
            }
        }else{
            $wechat = M('wechat')->where($eq)->find();
            $this->assign('list',$wechat);
            $this->display();
        }


    }
    //团队分红
    public function team(){
        if(IS_AJAX){
            $model = M('commission_team');
            $map = array();
            $map['tp_commission_team.wid'] = session('wid');
            $map['is_pay'] = 1;
            $res['count'] = $model->where($map)->count();
            $page = $_GET['page']?$_GET['page']:1;
            $limit = $_GET['limit']?$_GET['limit']:10;
            $list = $model->where($map)->join('tp_member m on m.mid = tp_commission_team.leaderid')->page("{$page},{$limit}")->select();
            $res['list']= $list;
            $this->ajaxReturn($res);
        }else{
            $this->display();

        }
    }

    public function edit_team(){
        $model = M("commission_team");
        $map['tp_commission_team.id'] = I('id');
        if(IS_AJAX){
            $data['team_name'] = I('team_name');
            $data['qrcode'] = I('imgurl');
            $re = $model->where($map)->save($data);
            if($re){
                $this->success('修改成功！');
            }else{
                $this->error('网络忙！');
            }
        }else{
            $re=$model->where($map)->join('tp_member m on m.mid = tp_commission_team.leaderid')->find();
            //var_dump($re);exit;
            $this->assign('vo',$re);
            $this->display();
        }

    }
    // 通过审核
    public function audit(){
    	$model = M("commission_team");
    	$map['id'] = I('id');
        $re=$model->where($map)->save(['status'=>1]);

        $info = $model->where($map)->find();
        //判断是直接申请会员，还是独立出来
        $mine = getMemberByMid(session('wid'),$info['leaderid']);
        if($mine['team_leader']==0){
            //修改我的下级，team_leader 为我的mid
            $sql = "select * from tp_member where FIND_IN_SET('{$info['leaderid']}',path)";
            $list = M()->query($sql);
            $users =array_column($list,'mid');
            $eq['mid'] = ['in',$users];
            $re2= M('member')->where($eq)->save(['team_leader'=>$info['leaderid']]);
        }else{
            $re2 = true;
        }
        //修改我的字段为队长
        $re3 = M('member')->where(['mid'=>$info['leaderid']])->save(['is_team_leader'=>1,'team_leader'=>0,'is_leader2'=>0]);
        if($re && $re2 && $re3){
            sendAuditMessage(I('id'),'team');
            $this->success('审核成功！');
        }else{
            $this->error('网络忙！');
        }
    }
    public function putmoney () {
        $wid = session('wid');
        $status = I('status');
        $info = M('commission_putmoney')->where(['wid' => $wid, 'status' => $status])->select();

        $this->assign('info', $info);
        $this->assign('status', $status);
        $this->display();
    }
    //通过审核
    public function commit () {
        $id = I('id');
        $wid = session('wid');
        $row = M('commission_putmoney')->where(['id' => $id, 'wid' => $wid])->save(['status' => 1]);
        
        $this->ajaxReturn($row ? 1 : 0);
    }
    //拒绝审核
    public function refuse () {
        $id = I('id');
        $wid = session('wid');
        $row = M('commission_putmoney')->where(['id' => $id, 'wid' => $wid])->save(['status' => 3]);

        $this->ajaxReturn($row ? 1 : 0);
    }
    //确认打款
    public function addMoney () {
        vendor('Weixinpay.WxRefund');
        M()->startTrans();
        $id = I('id');
        $wid = session('wid');
        $date = date('Y-m-d H:i:s', time());
        $info = M('Commission_putmoney')->where(['id' => $id, 'wid' => $wid])->find();

        //退款及发送消息
        $map['wid'] = $wid;
        $wechat = M("Wechat")->where($map)->find();
        $mchid = $wechat['mch_id'];                 //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
        $appid = $wechat['appid'];                  //微信支付申请对应的公众号的APPID
        $appKey = $wechat['app_secret'];            //微信支付申请对应的公众号的appsecret
        $apiKey = $wechat['partner_key'];           //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
        $openId = $info['openid'];                  //获取openid
        $wxpay = new \Wxrefund();
        //①、获取当前访问页面的用户openid（如果给指定用户转账，则直接填写指定用户的openid)
        $wxPay = new \WxRefund($mchid,$appid,$appKey,$apiKey);
        if(!$openId) exit('获取openid失败');
        //②、付款
        $outTradeNo = $this->build_order_no();      //订单号
        $payAmount = $info['really_money'];           //转账金额，单位:元。转账最小金额为1元
        $trueName = $info['realname'];                  //收款人真实姓名

        $result = $wxPay->createJsBizPackage($openId,$payAmount,$outTradeNo,$trueName);
        //var_dump($result);
        //成功
        if($result['result_code'] == "SUCCESS" && $result['return_code'] == "SUCCESS"){
            //发送模板消息
            $a = sendWithdrawMessage($info['openid'],$id);
            //将返回存入数据库
            $data['status'] =2;                                         //状态
            $data['partner_trade_no'] = $result['partner_trade_no'];    //自己生产的订单号
            $data['payment_no'] = $result['payment_no'];                //微信生成的订单号
            $data['remit_time'] = $result['payment_time'];              //打款时间
            $row = M('Commission_putmoney')->where(['id' => $id, 'wid' => $wid])->save($data);
            $mem = M('member')->where(['openid' => $info['openid']])->find();
            $row_1 = M('Commission')->where(['is_withdraw' => 0, 'wid' => $wid, 'mid' => $mem['mid']])->save(['is_withdraw' => 1]);
            if($row_1 && $row && $a){
                M()->commit();
                $this->ajaxReturn("打款成功");
            }else{
                M()->rollback();
                $this->ajaxReturn("打款失败，请重试！");
            }
        }else{
            $this->ajaxReturn($result['err_code_des']);
        }
    }
    protected function build_order_no(){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}